var Backbone = require('backbone');
var tpl = require('../tpl');
var NavModel = require('../model/nav');
var bus = require('bus');


var NAV_LIST = {
	profile: {},
	chat2: {},
	contacts: {}
};

module.exports = Backbone.View.extend({
	el: null,
	template: tpl.nav,
	events: {
		'click .J-im-nav-prev': 'prevPage',
		'click .J-im-nav-next': 'nextPage',
		'click .J-im-nav-more': 'more',
		'click .im-disabled': 'prevent'
	},
	initialize: function(options, api){
		this.model = this.model || new NavModel();
		this.api = api;
		
		// webapp 情况下, 列表页不显示后退
		/*if(this.api.sdk.isWebapp()){
			this.model.set({prev: false});
		}*/
		
		this.render();

		this.listenTo(this.model, 'change', this.render);
		this.listenTo(bus, 'changePage', this.changePage);
		this.listenTo(bus, 'statusChange', this.changeStatus);
	},
	render: function(){
		this.$el.html(this.template(this.api.servant.fuse(this.model, this.api.i18n.nav)));
	},
	prevent: function(e){
		e.preventDefault();
		e.stopPropagation();
	},
	title: function(val){
		this.model.set({
			title: val || ''
		}, {silent: true});
		
		this.model.trigger('change', {title: val});
	},
	changeStatus: function(uid, isOnline){
		// 在聊天页 聊天对象的上下线状态变更，及时显示其状态
		if(this.pageName === 'chat2' && uid === this.uid){
			this.model.set({
				online: isOnline
			});
		}
	},
	profile: function(page, pageName, uid){
		this.model.set({
			prev: '<',
			showOnline: false,
			next: false,
			more: this.api.i18n.nav.text.more
		});
	},
	_chat2: function(page, pageName, uid){
		var _this = this;
		
		this.api.sdk.getUserById(uid, function(user){
			if(user){
				_this.model.set({
					prev: '<',
					showOnline: true,
					title: user.name,
					online: !!user.online,
					next: 'profile',
					lnkNext: _this.api.path('profile/' + uid),
					more: false
				});
			}
		
		});
	},
	chat2: function(page, pageName, uid){
		var _this = this;
		
		if(this.api.isGetContacts){
			this._chat2(page, pageName, uid);
		}else{
			this.api.ready(function(){
				_this._chat2(page, pageName, uid);
			});
		}
	},
	contacts: function(page, pageName, uid){
		this.model.set({
			// webapp 情况下, 列表页不显示后退
			prev: !this.api.sdk.isWebapp(),
			showOnline: false,
			next: false,
			more: false
		});
	},
	changePage: function(page, pageName, uid){
		var _this = this;
		
		this.api.ready(function(){
			_this.page = page;
			_this.pageName = pageName;
			_this.uid = uid;
			
			_this.model.set({
				title: _this.api.servant.translate(_this.api.i18n.nav, pageName)
			}, {silent: true});
			
			
			_this[pageName](page, pageName, uid);
			_this.render();
		});
	},
	prevPage: function(e){
		e.preventDefault();
		this.api.backward();
	},
	nextPage: function(){
		//this.api.forward();
	},
	more: function(e){
		e.preventDefault();
		
		bus.trigger('moreProfile');
	},
	setModel: function(data){
		data && this.model.set(data);
	}
});